package com.zengdada.authority.utils;

import lombok.extern.slf4j.Slf4j;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2019-04-03 13:08
 * @Description:
 */
@Slf4j
public class CronUtils {

    /**
     * @param cronExpression cron表达式
     * @param numTimes       下一(几)次运行的时间
     * @return
     */
    public static List<Date> getRecentExecTime(String cronExpression, Integer numTimes) {
        try {
            CronTriggerImpl cronTrigger = new CronTriggerImpl();
            cronTrigger.setCronExpression(cronExpression);
            // 这个是重点，一行代码搞定
            return TriggerUtils.computeFireTimes(cronTrigger, null, numTimes);
        } catch (ParseException e) {
            log.error(e.getMessage());
        }
        return null;
    }

    public static boolean isValidExpression(final String cronExpression) {
        CronTriggerImpl trigger = new CronTriggerImpl();
        try {
            Date currentDate = new Date();
            trigger.setCronExpression(cronExpression);
            Date date = trigger.computeFirstFireTime(null);
            return date != null && (date.after(currentDate) || currentDate.getTime() / 1000 == date.getTime() / 1000);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }
}
